#include "clprs.h"

#define URL_STR		"udp://192.168.186.128:5555"
#define PORT		5555
#define AUDIO_CAPS	"application/x-rtp,media=(string)audio,clock-rate=(int)8000,encoding-name=(string)PCMU"
#define DEST_FILE	"./my.mp3"

static gboolean clprs_set_src(GstElement *udpsrc, clprs_uri_t *uri) 
{
	GstCaps *caps;

	g_assert (udpsrc);
	if(!uri){
		g_error("No uri presented!");
		return FALSE;
	}

	g_object_set (G_OBJECT (udpsrc), "uri", uri->uri_str, NULL);
	g_object_set (G_OBJECT (udpsrc), "port", uri->port, NULL);
	caps = gst_caps_from_string(AUDIO_CAPS);
	g_object_set(udpsrc, "caps", caps, NULL);
	gst_caps_unref (caps);

	return TRUE;
}

int main (int argc, char *argv[]) {
	gboolean link_ok;
	GMainLoop *loop;
	GstElement *pipeline, *udpsrc,  *rtppcmudepay, *mulawdec, *audioconvert, *lamemp3enc, *id3v2mux, *filesink;
	clprs_uri_t *uri;

	gst_init(&argc, &argv);
	loop = g_main_loop_new(NULL, FALSE);//create main loop
	
	uri = (clprs_uri_t*)g_malloc(sizeof(clprs_uri_t));
	uri->uri_str = g_strdup(URL_STR);
	uri->port = PORT;

	/* create a new pipeline */
	pipeline = gst_pipeline_new("pipeline");
	udpsrc = gst_element_factory_make("udpsrc", "rtpsrc");

	/* get date from uri=udp://192.168.186.128:5555 port=5555 */
	if(!clprs_set_src(udpsrc, uri)){
		g_error("Set uri err!!");
	}
	/* create elements */
	rtppcmudepay = gst_element_factory_make("rtppcmudepay", "rtppcmudepay");

	mulawdec = gst_element_factory_make("mulawdec", "pcmu_decoder");
	audioconvert = gst_element_factory_make("audioconvert", "audioconvert");
	lamemp3enc = gst_element_factory_make("lamemp3enc", "mp3_encoder");
	id3v2mux = gst_element_factory_make("id3v2mux", "mp3_mux");
	filesink = gst_element_factory_make("filesink", "sink");
	g_object_set (G_OBJECT (filesink), "location", DEST_FILE, NULL);

	/* add elements to pipeline */
	gst_bin_add_many (GST_BIN (pipeline), udpsrc, rtppcmudepay, mulawdec, audioconvert, lamemp3enc, id3v2mux, filesink, NULL);
	/* link elements */
	gst_element_link_many (udpsrc, rtppcmudepay, mulawdec, audioconvert, lamemp3enc, id3v2mux, filesink, NULL);

	/* play */
	gst_element_set_state (pipeline, GST_STATE_PLAYING);
	/* main loop */
	g_print("\nStart main loop ......\n");
	g_main_loop_run(loop);
	/* stop pipeline */
	gst_element_set_state (pipeline, GST_STATE_NULL);
	/* free src */
	g_free(uri->uri_str);
	gst_object_unref (GST_OBJECT (pipeline));
	exit (0);
}
